package com.unipay.user.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unipay.common.handler.UnipayException;
import com.unipay.common.helper.JwtHelper;
import com.unipay.common.result.ResultCodeEnum;
import com.unipay.enums.AuthStatusEnum;
import com.unipay.model.user.Patient;
import com.unipay.model.user.UserInfo;
import com.unipay.user.mapper.UserInfoMapper;
import com.unipay.user.service.PatientService;
import com.unipay.user.service.UserInfoService;
import com.unipay.vo.user.LoginVo;
import com.unipay.vo.user.UserAuthVo;
import com.unipay.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Project: yitong_parent
 * @Author: C.yu
 * @Time: 2023-05-01 09:12:51
 * @Desc: TODO
 */
@Service
@Transactional
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private PatientService patientService;

    //用户认证
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        //认证人姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    // 用户手机号登录接口
    @Override
    public Map<String, Object> userLogin(LoginVo loginVo) {
        // 1、从loginVo获取输入的手机号，和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        // 2、判断手机号和验证码，是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new UnipayException(ResultCodeEnum.PARAM_ERROR);
        }
        // TODO 3、判断手机验证码和输入的，验证码是否一致
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(redisCode)) {
            throw new UnipayException(ResultCodeEnum.CODE_ERROR);
        }

        // TODO 4、绑定手机号码：页面绑定手机号码会把openid传递过来，我们根据openid找到用户信息，然后绑定手机号码
        // 登录原则：要么直接手机号登录；要么微信登录，先获取微信信息openid等存入，然后绑定手机号，把手机号更新进去user_info库
        UserInfo userInfo = null;
        if (!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.selectWxInfoOpenId(loginVo.getOpenid());
            if (null != userInfo) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            } else {
                throw new UnipayException(ResultCodeEnum.DATA_ERROR);
            }
        }
        // userInfo=null 说明手机直接登录
        if (null == userInfo) {
            // 5、判断：如果userinfo为空，进行正常手机登录
            // 判断是否第一次登录：根据手机号查询数据库，如果不存在相同手机号就是第一次登录
            QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
            userInfoQueryWrapper.eq("phone", phone);
            userInfo = baseMapper.selectOne(userInfoQueryWrapper);
            if (userInfo == null) {
                //第一次使用这个手机号登录，添加信息到数据库
                userInfo = new UserInfo();
                //userInfo.setName("");
                userInfo.setName("firstName");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        }

        // 6、校验：是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new UnipayException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        // 7、若：不是第一次登录，直接登录。返回：登录信息、登录用户名、token信息
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        // TODO 判断改userInfo的name是否为空：是空，返回nickName；nickName也为空，则返回phone
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        // jwt生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        System.out.println("token: " + token);
        map.put("token", token);
        return map;
    }

    @Override
    public UserInfo selectWxInfoOpenId(String openid) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openid);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }

    // 用户列表分页
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> userInfoPage, UserInfoQueryVo userInfoQueryVo) {
        QueryWrapper<UserInfo> userInfoQueryWrapper = userInfoQueryVo.buildQueryWrapper();
        IPage<UserInfo> selectPage = baseMapper.selectPage(userInfoPage, userInfoQueryWrapper);
        //List<UserInfo> selectPageRecords = selectPage.getRecords();
        //System.out.println("page: " + selectPageRecords);
        selectPage.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });
        return selectPage;
    }

    @Override
    public Integer lock(Long userId, Integer status) {
        //int i = status.intValue();
        if (status.intValue() == 0 || status.intValue() == 1){
            //UserInfo userInfo = this.getById(userId);
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            int i = baseMapper.updateById(userInfo);
            return i;
        }else {
            throw new UnipayException(ResultCodeEnum.PARAM_ERROR);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 根据userid查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        UserInfo packageUserInfo = this.packageUserInfo(userInfo);
        map.put("userInfo", packageUserInfo);
        // 根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllByUserId(userId);
        map.put("patientList", patientList);
        return map;
    }

    @Override
    public Boolean approval(Long userId, Integer authStatus) {
        if (authStatus.intValue() == 2 || authStatus.intValue() == -1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            int i = baseMapper.updateById(userInfo);
            if (i > 0){
                return true;
            }else {
                return false;
            }
        }else {
            throw new UnipayException(ResultCodeEnum.PARAM_ERROR);
        }
    }

    // 封装：编号——>对应值
    private UserInfo packageUserInfo(UserInfo userInfo) {
        // 处理认证状态编码
        //Integer authStatus = userInfo.getAuthStatus();
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        // 处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue() == 0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString", statusString);
        return userInfo;
    }
}
